package com.scy.service;

import cn.hutool.core.util.IdUtil;
import com.scy.lock.DistributedLockFactory;
import com.scy.lock.RedisDistributedLock;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author：sichenyong
 * @Email: sichenyongwork@163.com
 * @Package：com.scy.service
 * @Project：Redis7NewDataStructure
 * @Date：2024/4/29 15:03
 * @description：
 */
@Service
@Slf4j
public class InventoryService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    String port;

    @Resource
    DistributedLockFactory distributedLockFactory;

    /**
     * 类似于CAS自旋锁的思想设置分布式锁、设置分布式锁的过期时间。
     * @return
     */
    public String sale() {
        String uuidValue = IdUtil.simpleUUID() + ":" + Thread.currentThread().getId();
        String retMsg;
        // LOCK
        Lock lock = distributedLockFactory.getDistributedLock("redis", uuidValue);

        lock.lock();

        // 拿到分布式锁
        try {
            //获取redis中的库存数据
            String inventory = stringRedisTemplate.opsForValue().get("inventory:001");

            int inventoryNumber = inventory == null ? 0 : Integer.parseInt(inventory);

            if (inventoryNumber > 0) {

                stringRedisTemplate.opsForValue().set("inventory:001",String.valueOf(-- inventoryNumber));
                retMsg = String.format("库存更新成功，当前库存：%s, 服务器端口：%s", inventoryNumber, port);
                log.info("库存更新成功，当前库存：{}, 服务器端口：{}", inventoryNumber, port);
            }
            else {
                retMsg = String.format("商品已经卖完了...... 服务器端口：%s",port);
                log.warn("商品已经卖完了...... 服务器端口：{}",port);
            }
        } finally {
            lock.unlock();
        }

        return retMsg;
    }
}
